package org.jeecg.modules.quartz.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qixin.modules.dataauth.entity.SysUserData;
import com.qixin.modules.dataauth.service.ISysUserDataService;
import org.jeecg.common.nc.enums.WSEnum;
import org.jeecg.common.nc.service.NCWebService;
import org.jeecg.common.nc.vo.WSVO;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.nc.entity.NcOrg;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecg.modules.quartz.entity.TbJobLog;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.jeecg.modules.quartz.service.ITbJobLogService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysDepartServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Map;

/**
 * NC用户同步
 */
public class NCUserSyncJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(NCUserSyncJob.class);

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    IQuartzJobService jobService;

    @Autowired
    private ITbJobLogService tbJobLogService;

    @Autowired
    private INcPersonnelService ncPersonnelService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    SysDepartServiceImpl sysDepartService;

    @Value("${qixin.ncserver.uri}")
    private String NC_SERVER_URI;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        String lastTime = jobService.queryLastTime("ncusersyncjob");
        String currentTime = DateUtil.now();
        Boolean first = false;
        if (StrUtil.isBlank(lastTime)){
            lastTime = "2008-01-01 00:00:00";
            first = true; // 表示第一次同步
        }

        // 获取NC组织数据
        try {
            // 获取组织个数
            List<NcOrg> ncOrgs = sysDepartService.querOrgList();
            WSVO vo = new WSVO();
            if (ncOrgs.size() > 0) {
                // 循环组织名称更新人员档案
                for (NcOrg ncOrg : ncOrgs) {
                    WSEnum.USER.setMsg(ncOrg.getCode());
                    vo = NCWebService.getFromWS(NC_SERVER_URI, WSEnum.USER,lastTime);
                    for (Map<String, Object> map : vo.getContent()) {
                        SysUser user =  new SysUser();
                        String pkPsndoc = (String) map.get("pk_psndoc"); // 人员主键
                        String islocked = (String) map.get("islocked");
                        String enablestate = map.get("enablestate").toString();
                        user.setId((String) map.get("cuserid"));
                        user.setUsername((String) map.get("user_code")); // 登陆账号
                        user.setRealname((String)map.get("user_name"));
                        user.setPkPsndoc((String)map.get("pk_psndoc")); // 人员档案主键
                        user.setStatus(1); // 状态(1：正常  2：冻结 ）
                        if(!"N".equals(islocked) || !"2".equals(enablestate)){
                            user.setStatus(2);
                        }
                        if(StrUtil.isNotBlank(pkPsndoc)){
                            // 获取用户对应人员的部门信息
                            NcPersonnel ncPersonnel = ncPersonnelService.queryById(pkPsndoc);
                            if (ncPersonnel != null){
                                // 在表sys_user_depart 添加用户与部门的对应关系
                                SysUserDepart sysUserDepart2 = sysUserDepartService.queryByUserid(user.getId());
                                if(sysUserDepart2 == null){
                                    // 数据不存在
                                    SysUserDepart sysUserDepart = new SysUserDepart(user.getId(),ncPersonnel.getPkDept());
                                    sysUserDepartService.save(sysUserDepart);
                                }else{
                                    // 数据存在 那就更新一下
                                    sysUserDepart2.setUserId(user.getId());
                                    sysUserDepart2.setDepId(ncPersonnel.getPkDept());
                                    sysUserDepartService.updateById(sysUserDepart2);
                                }
                            }
                        }
                        QueryWrapper queryWrapper = new QueryWrapper();
                        queryWrapper.eq("id",(String) map.get("cuserid"));
                        Integer count = sysUserService.count(queryWrapper);
                        if(count == 0){
                            String salt = oConvertUtils.randomGen(8);
                            user.setSalt(salt);
                            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), "1234@qwer", salt); // 设置默认密码
                            user.setPassword(passwordEncode);
                        }

                        //user.setOrgCode((String) map.get("pk_org"));
                        user.setOrigin("NC6.5");
                        user.setDelFlag((Integer) map.get("dr"));
                        user.setUserType(1);
                        sysUserService.saveOrUpdate(user);
                    }
                    TbJobLog tbJobLog = new TbJobLog();
                    tbJobLog.setName(ncOrg.getName() + "NC用户同步");
                    tbJobLog.setContent(ncOrg.getName() + "本次新增或更新记录" + vo.getContent().size() + "条");
                    tbJobLog.setNum(vo.getContent().size());
                    tbJobLogService.save(tbJobLog);
                }
                if(first){
                    // 新增一条记录
                    jobService.insetLastTime("ncusersyncjob", currentTime);
                }else{
                    //更新最后同步时间
                    jobService.updateLastTime("ncusersyncjob", currentTime);
                }
                logger.info("NC用户同步成功更新：{}条", vo.getContent().size());
            }


        } catch (Exception e) {
            logger.info("NC用户同步出现异常：{}", e.getMessage());
            e.printStackTrace();
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC用户同步");
            tbJobLog.setContent("同步出现异常：" + e.getMessage());
            tbJobLog.setNum(0);
            tbJobLogService.save(tbJobLog);
        }

    }
}
